package com.agent.common.utils;

import cn.hutool.core.util.StrUtil;
import com.agent.common.entity.UserContext;
import com.agent.common.exception.AuthenticationException;
import com.agent.common.result.ResultCode;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户信息提取工具类
 * <p>
 * 提供从当前请求中提取用户信息的便捷方法
 */
public class UserInfoUtils {

    private static final String AUTH_HEADER = "Authorization";
    private static final String BEARER_PREFIX = "Bearer ";
    
    private UserInfoUtils() {
        // 工具类不允许实例化
    }

    /**
     * 从当前请求中提取用户上下文
     */
    public static UserContext getCurrentUserContext() {
        HttpServletRequest request = getCurrentRequest();
        String token = extractToken(request);
        return getUserContextFromToken(token);
    }

    /**
     * 获取当前用户ID
     * @return 用户ID
     */
    public static Long getUserId() {
        UserContext context = getCurrentUserContext();
        return context != null && context.getUserId() != null ? context.getUserId() : null;
    }

    /**
     * 获取当前用户名
     * @return 用户名
     */
    public static String getUsername() {
        UserContext context = getCurrentUserContext();
        return context != null && context.getUsername() != null ? context.getUsername() : null;
    }

    /**
     * 获取当前会员类型
     * @return 会员类型
     */
    public static String getMembershipType() {
        UserContext context = getCurrentUserContext();
        return context != null && context.getMembershipType() != null ? context.getMembershipType() : null;
    }

    /**
     * 从令牌中提取用户上下文
     */
    public static UserContext getUserContextFromToken(String token) {
        if (token == null || StrUtil.isBlank(token)) {
            throw new AuthenticationException(ResultCode.UNAUTHORIZED);
        }
        
        try {
            // 自动检测令牌类型（RSA/HMAC）
            boolean isRsaToken = token.length() > 150; // 简单启发式判断
            return JwtUtils.getInstance().extractUserContext(token, isRsaToken);
        } catch (Exception e) {
            throw new AuthenticationException(ResultCode.UNAUTHORIZED, "Failed to extract user context from token: " + e.getMessage());
        }
    }

    /**
     * 从请求中提取令牌
     */
    private static String extractToken(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        
        String header = request.getHeader(AUTH_HEADER);
        if (header != null && header.startsWith(BEARER_PREFIX)) {
            return header.substring(BEARER_PREFIX.length());
        }
        return null;
    }

    /**
     * 获取当前HTTP请求
     */
    private static HttpServletRequest getCurrentRequest() {
        try {
            return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        } catch (IllegalStateException e) {
            // 非Web请求环境
            return null;
        }
    }
}